import * as THREE from './three.weapp.js'
GLTFLoader = getGLTFLoader(THREE);
            
let { SkeletonUtils } = getSkeletonUtils(THREE);
const deviceOrientationControl = require('DeviceOrientationControl2.js');
// const { getGLTFLoader } = require('GLTFLoader.js');
import getGLTFLoader from 'GLTFLoader2' 
import getSkeletonUtils from 'SkeletonUtils2.js';

const deviceMotionInterval = 'normal';
var camera, scene, renderer,pages,prevPage;
var canvas,poid;
var touchX, touchY, device = {};
var lon, lat,GLTFLoader, gradient, clock, mixer, controls, action, activeAction, face, actions;
// var THREE;
var seletedModel, requestId,requestId2,monsmsg,name1,name2,modelUrl,isstop=1,times=1
var isDeviceMotion = false ,isAndroid = false;
var last_lon, last_lat, last_device = {};
var cameraFrame = {};
var models;
var MODELS = [];

var worldScene = null;
var mixers = []; 
var numLoadedModels = 0;
var UNITS=[]
// 获取参数:画布id，模型名、网格名、（动画名）
function initThree(canvasId,name1,name2,name3,callback) {
    if (name1=="gbsz"){
        models = "2act"
    }else{
        models = "shibing"
    }
    modelUrl='https://www.juquduo.com/static/models/test/'+ models+'.glb'
    var aniname1=name3.split("_")[1];
    console.log('aniname1',aniname1)
    MODELS = [
        { name : name1}
    ];
    UNITS=[{
        modelName: name1,
        position: { x: 2, y: -6, z: 0 },
        // scale: 0.6,
        scale: 2,
        meshName: name2,
        animationName: aniname1       //gedou2
    },{
        modelName: name1,
        position: { x: 2, y: -4, z: 0 },
        scale: 2,
        meshName: "mixamorig_Hips",animationName: "2"       //gedou2
    }]
    wx.createSelectorQuery()
        .select('#' + canvasId)
        .node()
        .exec((res) => {
			canvas = new THREE.global.registerCanvas(res[0].node)
            clock = new THREE.Clock();

            worldScene = new THREE.Scene();
            if (typeof callback === 'function') {
                callback(THREE);
            }
            playani()
            animate()
            console.log('模型绑定到画布')
        });
}
// 初始化场景，设置场景参数，添加光源，设置完之后加载模型
function initScene() {
    lon = 30;
    lat = 190;
    camera = new THREE.PerspectiveCamera(75,
        canvas.width / canvas.height,
        1,
        1000);
    scene = new THREE.Scene();
    worldScene.add(new THREE.AmbientLight(0xffffff));
    var light = new THREE.HemisphereLight(0xffffff, 0x444444);
    light.position.set(0, 20, 0);
    worldScene.add(light);
    light = new THREE.DirectionalLight(0xffffff);
    light.position.set(0, 20, 10);
    worldScene.add(light);
    console.log('worldScene',worldScene)
    renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true,
    });
    console.log('canvas size', canvas.width, canvas.height);
    console.log('renderer', renderer);
    renderer.setSize(canvas.width, canvas.height);
    // camera.position.set( 3, 3, 6 );
    camera.position.set( 2, 1, 8 );
    loadModels();
}
//判断模型数量，调用下载模型方法
function loadModels() {
    console.log('开始加载模型')
    pages = getCurrentPages();
    prevPage = pages[pages.length-1]
    console.log('pages',pages)
    console.log('prevPage',prevPage)
    prevPage.startloadmodel()
    for (var i = 0; i < MODELS.length; ++i) {
        var m = MODELS[i];
        loadGltfModel(m, function () {
            ++numLoadedModels;
            if (numLoadedModels === MODELS.length) {
                console.log("All models loaded, time to instantiate units...");
                // start2(0)   //加载完模型后播放动画
            }
        });
        console.log('模型加载数量',i+1)
    }
}
function createElementMaterial() {

    var material = new THREE.MeshBasicMaterial(); // create a material

    var loader = new THREE.TextureLoader().load(
        // resource URL
        IMG_MACHINE,
        // Function when resource is loaded
        function ( texture ) {
            // do something with the texture
                texture.wrapS = THREE.RepeatWrapping;
                texture.wrapT = THREE.RepeatWrapping;
                texture.offset.x = 90/(2*Math.PI);
                material.map = texture; // set the material's map when when the texture is loaded
        },
        // Function called when download progresses
        function ( xhr ) {
            console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
        },
        // Function called when download errors
        function ( xhr ) {
            console.log( 'An error happened' );
        }
    );
    return material; // return the material
}
//加载器加载模型，onloaded是方法，调用加载动画的方法start2
function loadGltfModel(model, onLoaded) {
    var loader = new GLTFLoader();
    var modelName = "models/" + model.name + ".glb";
    
    //     var texture
    //     var txloader = new THREE.TextureLoader();
    //      texture = txloader.load("https://www.juquduo.com/static/models/cygy/jiangjun.glb");
    // texture.minFilter = THREE.LinearFilter
        
    // loader .load("https://www.juquduo.com/static/models/cygy/general.glb", function (gltf) {
    // loader .load("https://www.juquduo.com/static/models/cygy/333.glb", function (gltf) {
    loader.load("https://www.juquduo.com/static/models/gbsz/shibing.glb", function (gltf) {
    // loader.load("https://www.juquduo.com/static/models/cygy/jiangjun.glb", function (gltf) {
    // loader.load('http://192.168.1.107:5500/fbx文件/act.glb', function (gltf) {
    // loader.load(modelUrl, function (gltf) {

        prevPage.modelloaded()
        var scene = gltf.scene;
        model.animations = gltf.animations;
        model.scene = scene;
        gltf.scene.traverse(function (object) {
            if (object.isMesh) {
                object.castShadow = true;
            }
        });
        console.log("Done loading model", model.name);
        onLoaded();
    });
}
// 添加动画时,用于获取模型
function getModelByName(name) {
    for (var i = 0; i < MODELS.length; ++i) {
        if (MODELS[i].name === name) {
            return MODELS[i];
        }
    }
    return null;
}
// 添加动画
function start2(isstop){
    // 在场景里，删掉之前的动画，保留灯光等效果
    
    if(worldScene.children.length>3){worldScene.children.splice(3)}
    //获取模型、场景、网格、播放器、动画动作 等对象
    var u = UNITS[0];
    var model = getModelByName(u.modelName);
    var clonedScene = SkeletonUtils.clone(model.scene);
    clonedScene.scale.set(u.scale, u.scale, u.scale);   //设置场景，设置缩放倍数、观察位置
    clonedScene.position.set(u.position.x, u.position.y, u.position.z);
    clonedScene.rotation.y = 0.3;
    // clonedScene.rotation.x = -1.8;
    // var clonedMesh = clonedScene.getObjectByName(u.meshName);
    var clonedMesh = clonedScene.getObjectByName('mixamorig_Hips');
    worldScene.add(clonedScene);        //场景添加到屏幕场景
    // console.log('添加完动作',worldScene.children)     //查看屏幕场景的当前信息
    // console.log(model.animations)
    var mixer = model.mixer = new THREE.AnimationMixer(model);      //获取播放器
    var clip = model.animations[isstop]
    if(clip){
        var AnimationAction =mixer.clipAction( clip, clonedMesh)    //给播放器添加动画
        // 设置动画动作
        AnimationAction.setLoop( THREE.LoopOnce )   //播放一次就停止
        AnimationAction.clampWhenFinished = true;   //播放停止在最后一帧
        AnimationAction.play();
        mixers.push(mixer);
    }
}
//动画，计算手机移动，旋转模型
function animate() {
    
    requestId2 = canvas.requestAnimationFrame(animate);

    if (lon !== last_lon ||
        lat !== last_lat) {

        last_lon = lon;
        last_lat = lat;

        deviceOrientationControl.modelRotationControl(seletedModel, lon, lat, gradient, THREE);
    }

    if (last_device.alpha !== device.alpha ||
        last_device.beta !== device.beta ||
        last_device.gamma !== device.gamma) {

        last_device.alpha = device.alpha;
        last_device.beta = device.beta;
        last_device.gamma = device.gamma;

        if (isDeviceMotion) {
            deviceOrientationControl.deviceControl(camera, device, THREE, isAndroid);
        }
    }
    renderer.render(worldScene, camera);
}
// 每帧刷新，每帧调用一次，用于播放动画，把sence渲染到屏幕
function playani() {
    var dt = clock.getDelta();
    // if (mixer) mixer.update(dt);
    for (var i = 0; i < mixers.length; ++i) {
        mixers[i].update(dt);
    }
    // console.log('刷新动画')
    requestId = canvas.requestAnimationFrame(playani,animate);
    renderer.render(worldScene, camera);
    // console.log('每帧刷新')
  }
// 停止动画，修改参数，停止渲染的request
function stopanimate() {
    if (canvas && requestId) {
        canvas.cancelAnimationFrame(requestId);
        canvas.cancelAnimationFrame(requestId2);
    }
    worldScene=''
    numLoadedModels = 0
    renderer = null;
    // renderer.domElement = null;
    // renderer.dispose();
    // renderer.forceContextLoss();
}

function onTouchstart(event) {
    var touch = event.touches[0];
    touchX = touch.x;
    touchY = touch.y;
}

function onTouchmove(event) {
    var touch = event.touches[0];
    var moveX = touch.x - touchX;
    var moveY = touch.y - touchY;
    lon += moveX;
    lat += moveY;
    touchX = touch.x;
    touchY = touch.y;
    gradient = Math.abs(moveX / moveY);
}

function startDeviceMotion(_isAndroid) {
    isDeviceMotion = true;
    isAndroid = _isAndroid;
    wx.onDeviceMotionChange(function (_device) {
        device = _device;
        // console.log('rotate')
    });
    wx.startDeviceMotionListening({
        interval: deviceMotionInterval,
        success: function () {
            console.log('startDeviceMotionListening', 'success');
        },
        fail: function (error) {
            console.log('startDeviceMotionListening', error);
        }
    });
}

function stopDeviceMotion() {
    isDeviceMotion = false;
    wx.offDeviceMotionChange();
    wx.stopDeviceMotionListening({
        success: function () {
            console.log('stopDeviceMotionListening', 'success');
        },
        fail: function (error) {
            console.log('stopDeviceMotionListening', error);
        }
    });
}

function setCameraFrame(_cameraFrame) {
    cameraFrame = _cameraFrame;
}
function duizhun(_isAndroid){
    isAndroid = _isAndroid;
    var keyida
    var fx=device.alpha
    var jd=device.beta
    console.log(fx,jd)
    if((fx > 340 || fx < 30)&&(jd > -95 && jd < -20)&&isAndroid){
        keyida = 2
    }else if((fx > 350 || fx < 20)&&(jd < 95 && jd > 20)&& !isAndroid){
        keyida = 2
    } else{
        keyida = 1
    }
    return keyida
}
module.exports = {
    initThree,
    initScene,
    onTouchstart,
    onTouchmove,
    startDeviceMotion,
    stopDeviceMotion,
    stopanimate,
    setCameraFrame,
    UNITS,
    start2,
    duizhun,
}